package com.authine.cloudpivot.ext.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectQueryModel;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.PageableImpl;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.engine.enums.ErrCode;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.engine.enums.type.DefaultPropertyType;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.exception.PortalException;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;


@RestController
@RequestMapping("/public/aliInterface")
@Slf4j
public class AliInterfaceController extends BaseController {

    @Autowired
    CloudSqlService sqlService;
    @Autowired
    private RedissonClient redisson;
    @Autowired
    private RedisTemplate redisTemplate;


    ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(10);


    /**
     * 更改出入库表流程id生成规则
     *
     * @param objId
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/changeRuleBySequenceNo", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value = "更改表流程id生成规则", notes = "更改表流程id生成规则")
    public void changeRuleBySequenceNo(String objId, String SchemaCode, String SubSheet, String suffix) {
        log.info("获取参数:objId={},SchemaCode={},suffix={}", objId, SchemaCode, suffix);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(SchemaCode)) {
            log.info("参数不完整，直接结束");
            return;
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();



        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(SchemaCode, objId);
        String billNoByObjId = bizObject.getString("billNo");
        if (StringUtils.isNotBlank(billNoByObjId)) {
            //已生成单据编号，不继续生成新的单据编号
            return;
        }


//        if (bizObject == null) {
//            log.info("业务对象不存在");
//            return;
//        }
        //单据号
//        String sequenceNo = bizObject.getSequenceNo();
//        log.info("\n===============1-sequenceNo:{}", sequenceNo);

        String schemaCodeTableName = bizObjectFacade.getTableName(SchemaCode);
        //查询单据号
        Calendar instance = Calendar.getInstance();
        Date nowTime = instance.getTime();
        String format = DateFormatUtils.format(nowTime, "yyyy-MM-dd");
        String startTimeString = new StringBuffer(format).append(" 00:00:00").toString();
        String endTimeString = new StringBuffer(format).append(" 23:59:59").toString();
        log.info("startTimeString：{}，endTimeString：{}", startTimeString, endTimeString);
        StringBuffer sqlCount = new StringBuffer("select billNo from ").append(schemaCodeTableName).append(" where sequenceStatus != 'DRAFT' and billNo is not null and billNo != '' and  createdTime >= '")
                .append(startTimeString).append("' and createdTime <= '").append(endTimeString).append("' ORDER BY createdTime desc limit 1");
        Map<String, Object> djhCount = sqlService.getMap(sqlCount.toString());
        log.info("djhCount：{}", JSONObject.toJSONString(djhCount));
        String sequenceNo = "";
        String format2 = DateFormatUtils.format(nowTime, "yyyyMMdd");
        String billNoForLast2 = MapUtils.getString(djhCount, "billNo");
        if (djhCount == null || djhCount.size() == 0) {
            sequenceNo = new StringBuffer(format2).append("-").append(String.format("%03d", 1)).toString();
        } else {
            String substring = billNoForLast2.substring(billNoForLast2.length() - 3, billNoForLast2.length());
            int i = Integer.parseInt(substring) + 1;
            sequenceNo = new StringBuffer(format2).append("-").append(String.format("%03d", i)).toString();
        }


        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(SubSheet);
        //获取子表对应字段

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String seqNo = simpleDateFormat.format(new Date());
        log.info("\n===============2-seqNo:{}", seqNo);
        if (StringUtils.isNoneBlank(sequenceNo)) {
            sequenceNo = seqNo + "-" + sequenceNo.substring(sequenceNo.length() - 3, sequenceNo.length());
            log.info("\n===============2-sequenceNo:{}", sequenceNo);
        }
        String billNo = suffix + "-" + sequenceNo;
        bizObject.put("billNo", billNo);
        //bizObject.put("name",bizObject.getCreater().getName()+"的 "+sequenceNo);
        bizObject.put("name", billNo);

        String workflowInstanceId = bizObject.getWorkflowInstanceId();

        scheduledExecutorService.schedule(() -> {
            if (StringUtils.isNotEmpty(workflowInstanceId)) {
                    log.info("流程id存在:{}", workflowInstanceId);

                StringBuilder sql = new StringBuilder("update biz_workflow_instance set instanceName='")
                        .append(billNo).append("' where id='").append(workflowInstanceId).append("';");
                log.info("更新流程名称");
                sqlService.update(sql.toString());

                sql = new StringBuilder(" update biz_workitem set instanceName='").append(billNo).append("' where instanceId='")
                        .append(workflowInstanceId).append("';");
                log.info("更新待办流程名称");
                sqlService.update(sql.toString());

                log.info("更新已办流程名称");
                sql = new StringBuilder(" update biz_workitem_finished set instanceName='").append(billNo).append("' where instanceId='")
                        .append(workflowInstanceId).append("';");
            }

            getBizObjectFacade().saveBizObject("2c9280a26706a73a016706a93ccf002b", bizObject, Boolean.TRUE);
        }, 3, TimeUnit.SECONDS);


    }


    /**
     * 更改出表流程id生成规则 02-FU-N-20220903-003
     * FormFieldValue 表单字段，SchemaCode 模型编码,suffix 后缀 如：FU-N
     *
     * @param objId
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/changeRuleBySequenceNoExample01", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value = "更改表流程id生成规则", notes = "更改表流程id生成规则")
    public void changeRuleBySequenceNoExample01(String objId, String SchemaCode, String FormFieldValue, String SubSheet, String suffix) {
        log.info("获取参数:objId={},SchemaCode={},FormFieldValue={},suffix={}", objId, SchemaCode, FormFieldValue, suffix);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(SchemaCode)) {
            log.info("参数不完整，直接结束");
            return;
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();

//        //因为节点是异步，单据号生成时好时不好怀疑代码进入，bizobject还没有生成，由于是节点简单处理直接sleep(并且不存在的id bizobject也不会为空）
//        for (int i = 0; i < 10 &&BooleanUtils.isNotTrue(bizObjectFacade.getBizObject(SchemaCode, objId).getLoadedFromDb()); i++) {
//            if(i==9){
//                log.info("业务对象不存在");
//                return ;
//            }
//            Thread.sleep(1000);
//        }
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(SchemaCode, objId);
        String billNoByObjId = bizObject.getString("billNo");
        if (StringUtils.isNotBlank(billNoByObjId)) {
            //已生成单据编号，不继续生成新的单据编号
            return;
        }


//        if (bizObject == null) {
//            log.info("业务对象不存在");
//            return;
//        }
//        //单据号
//        String sequenceNo = bizObject.getSequenceNo();
//        log.info("\n===============1-sequenceNo:{}", sequenceNo);

        String schemaCodeTableName = bizObjectFacade.getTableName(SchemaCode);
        //查询单据号
        Calendar instance = Calendar.getInstance();
        Date nowTime = instance.getTime();
        String format = DateFormatUtils.format(nowTime, "yyyy-MM-dd");
        String startTimeString = new StringBuffer(format).append(" 00:00:00").toString();
        String endTimeString = new StringBuffer(format).append(" 23:59:59").toString();
        log.info("startTimeString：{}，endTimeString：{}", startTimeString, endTimeString);
        StringBuffer sqlCount = new StringBuffer("select billNo from ").append(schemaCodeTableName).append(" where sequenceStatus != 'DRAFT' and billNo is not null and billNo != '' and createdTime >= '")
                .append(startTimeString).append("' and createdTime <= '").append(endTimeString).append("' ORDER BY createdTime desc limit 1");
        Map<String, Object> djhCount = sqlService.getMap(sqlCount.toString());
        log.info("djhCount：{}", JSONObject.toJSONString(djhCount));
        String sequenceNo = "";
        String format2 = DateFormatUtils.format(nowTime, "yyyyMMdd");
        String billNoForLast2 = MapUtils.getString(djhCount, "billNo");
        if (djhCount == null || djhCount.size() == 0) {
            sequenceNo = new StringBuffer(format2).append("-").append(String.format("%03d", 1)).toString();
        } else {
            String substring = billNoForLast2.substring(billNoForLast2.length() - 3, billNoForLast2.length());
            int i = Integer.parseInt(substring) + 1;
            sequenceNo = new StringBuffer(format2).append("-").append(String.format("%03d", i)).toString();
        }
        log.info("最终生成的单据号：{}", sequenceNo);

        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(SubSheet);
        //获取子表/主表对应字段
        String paramCode = (String) list.get(0).get(FormFieldValue);
        paramCode = StringUtils.isBlank(paramCode) ? (String) bizObject.get(FormFieldValue) : paramCode;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String seqNo = simpleDateFormat.format(new Date());
        log.info("\n===============2-seqNo:{}", seqNo);
        if (StringUtils.isNoneBlank(sequenceNo)) {
            sequenceNo = seqNo + "-" + sequenceNo.substring(sequenceNo.length() - 3, sequenceNo.length());
            log.info("\n===============2-sequenceNo:{}", sequenceNo);
        }

        if (StringUtils.isBlank(FormFieldValue)) {
            sequenceNo = suffix + "-" + sequenceNo;
        } else {
            sequenceNo = paramCode + "-" + suffix + "-" + sequenceNo;
        }
        String billNo = sequenceNo;
        bizObject.put("billNo", billNo);
        //bizObject.put("name",bizObject.getCreater().getName()+"的 "+sequenceNo);
        bizObject.put("name", billNo);

        String workflowInstanceId = bizObject.getWorkflowInstanceId();

        scheduledExecutorService.schedule(() -> {
            if (StringUtils.isNotEmpty(workflowInstanceId)) {
                log.info("流程id存在:{}", workflowInstanceId);

                StringBuilder sql = new StringBuilder("update biz_workflow_instance set instanceName='")
                        .append(billNo).append("' where id='").append(workflowInstanceId).append("';");
                log.info("更新流程名称");
                sqlService.update(sql.toString());

                sql = new StringBuilder(" update biz_workitem set instanceName='").append(billNo).append("' where instanceId='")
                        .append(workflowInstanceId).append("';");
                log.info("更新待办流程名称");
                sqlService.update(sql.toString());

                log.info("更新已办流程名称");
                sql = new StringBuilder(" update biz_workitem_finished set instanceName='").append(billNo).append("' where instanceId='")
                        .append(workflowInstanceId).append("';");
            }
            getBizObjectFacade().saveBizObject("2c9280a26706a73a016706a93ccf002b", bizObject, Boolean.TRUE);
        }, 3, TimeUnit.SECONDS);

    }

    /**
     * 更改出表流程id生成规则 02-FU-N-20220903-003
     * FormFieldValue 表单字段，SchemaCode 模型编码,suffix 后缀 如：FU-N
     *
     * @param objId
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/changeRuleBySequenceNoExample01Test", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value = "更改表流程id生成规则", notes = "更改表流程id生成规则")
    public String changeRuleBySequenceNoExample01Test(String objId, String SchemaCode, String FormFieldValue, String SubSheet, String suffix) {
        log.info("获取参数:objId={},SchemaCode={},FormFieldValue={},suffix={}", objId, SchemaCode, FormFieldValue, suffix);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(SchemaCode)) {
            log.info("参数不完整，直接结束");
            return objId;
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();


//        //因为节点是异步，单据号生成时好时不好怀疑代码进入，bizobject还没有生成，由于是节点简单处理直接sleep(并且不存在的id bizobject也不会为空）
//        for (int i = 0; i < 10 &&BooleanUtils.isNotTrue(bizObjectFacade.getBizObject(SchemaCode, objId).getLoadedFromDb()); i++) {
//            if(i==9){
//                log.info("业务对象不存在");
//                return objId;
//            }
//            Thread.sleep(1000);
//        }
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(SchemaCode, objId);
        String billNoByObjId = bizObject.getString("billNo");
        if (StringUtils.isNotBlank(billNoByObjId)) {
            return "已生成单据编号，不继续生成新的单据编号";
        }



//        if (bizObject == null) {
//            log.info("业务对象不存在");
//            return objId;
//        }
        //单据号
//        String sequenceNo = bizObject.getSequenceNo();
//        log.info("\n===============1-sequenceNo:{}", sequenceNo);

        String schemaCodeTableName = bizObjectFacade.getTableName(SchemaCode);
        //查询单据号
        Calendar instance = Calendar.getInstance();
        Date nowTime = instance.getTime();
        String format = DateFormatUtils.format(nowTime, "yyyy-MM-dd");
        String startTimeString = new StringBuffer(format).append(" 00:00:00").toString();
        String endTimeString = new StringBuffer(format).append(" 23:59:59").toString();
        log.info("startTimeString：{}，endTimeString：{}", startTimeString, endTimeString);
        StringBuffer sqlCount = new StringBuffer("select billNo from ").append(schemaCodeTableName).append(" where sequenceStatus != 'DRAFT' and billNo is not null and billNo != '' and createdTime >= '")
                .append(startTimeString).append("' and createdTime <= '").append(endTimeString).append("' ORDER BY createdTime desc limit 1");
        Map<String, Object> djhCount = sqlService.getMap(sqlCount.toString());
        log.info("djhCount：{}", JSONObject.toJSONString(djhCount));
        String sequenceNo = "";
        String format2 = DateFormatUtils.format(nowTime, "yyyyMMdd");
        String billNoForLast2 = MapUtils.getString(djhCount, "billNo");
        if (djhCount == null || djhCount.size() == 0) {
            sequenceNo = new StringBuffer(format2).append("-").append(String.format("%03d", 1)).toString();
        } else {
            String substring = billNoForLast2.substring(billNoForLast2.length() - 3, billNoForLast2.length());
            int i = Integer.parseInt(substring) + 1;
            sequenceNo = new StringBuffer(format2).append("-").append(String.format("%03d", i)).toString();
        }
        log.info("changeRuleBySequenceNoExample01Test 最终生成的单据号：{}", sequenceNo);

        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(SubSheet);
        //获取子表/主表对应字段
        String paramCode = (String) list.get(0).get(FormFieldValue);
        paramCode = StringUtils.isBlank(paramCode) ? (String) bizObject.get(FormFieldValue) : paramCode;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String seqNo = simpleDateFormat.format(new Date());
        log.info("\n===============2-seqNo:{}", seqNo);
        if (StringUtils.isNoneBlank(sequenceNo)) {
            sequenceNo = seqNo + "-" + sequenceNo.substring(sequenceNo.length() - 3, sequenceNo.length());
            log.info("\n===============2-sequenceNo:{}", sequenceNo);
        }

        if (StringUtils.isBlank(FormFieldValue)) {
            sequenceNo = suffix + "-" + sequenceNo;
        } else {
            sequenceNo = paramCode + "-" + suffix + "-" + sequenceNo;
        }
        String billNo = sequenceNo;
        bizObject.put("billNo", billNo);
        //bizObject.put("name",bizObject.getCreater().getName()+"的 "+sequenceNo);
        bizObject.put("name", billNo);

        String workflowInstanceId = bizObject.getWorkflowInstanceId();

        scheduledExecutorService.schedule(() -> {
            if (StringUtils.isNotEmpty(workflowInstanceId)) {
                log.info("流程id存在:{}", workflowInstanceId);

                StringBuilder sql = new StringBuilder("update biz_workflow_instance set instanceName='")
                        .append(billNo).append("' where id='").append(workflowInstanceId).append("';");
                log.info("更新流程名称");
                sqlService.update(sql.toString());

                sql = new StringBuilder(" update biz_workitem set instanceName='").append(billNo).append("' where instanceId='")
                        .append(workflowInstanceId).append("';");
                log.info("更新待办流程名称");
                sqlService.update(sql.toString());

                log.info("更新已办流程名称");
                sql = new StringBuilder(" update biz_workitem_finished set instanceName='").append(billNo).append("' where instanceId='")
                        .append(workflowInstanceId).append("';");
            }

            getBizObjectFacade().saveBizObject("2c9280a26706a73a016706a93ccf002b", bizObject, Boolean.TRUE);
        }, 3, TimeUnit.SECONDS);

        return billNo;
    }

    /**
     * 更改出表流程id生成规则 FU-N-02-20220903-003
     * FormFieldValue 表单字段，SchemaCode 模型编码,suffix 后缀 如：FU-N
     *
     * @param objId
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/changeRuleBySequenceNoExample03", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value = "更改表流程id生成规则", notes = "更改表流程id生成规则")
    public void changeRuleBySequenceNoExample03(String objId, String SchemaCode, String FormFieldValue, String SubSheet, String suffix) {
        log.info("获取参数:objId={},SchemaCode={},FormFieldValue={},suffix={}", objId, SchemaCode, FormFieldValue, suffix);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(SchemaCode)) {
            log.info("参数不完整，直接结束");
            return;
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();

//        //因为节点是异步，单据号生成时好时不好怀疑代码进入，bizobject还没有生成，由于是节点简单处理直接sleep(并且不存在的id bizobject也不会为空）
//        for (int i = 0; i < 10 &&BooleanUtils.isNotTrue(bizObjectFacade.getBizObject(SchemaCode, objId).getLoadedFromDb()); i++) {
//            if(i==9){
//                log.info("业务对象不存在");
//                return ;
//            }
//            Thread.sleep(1000);
//        }
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(SchemaCode, objId);

        String billNoByObjId = bizObject.getString("billNo");
        if (StringUtils.isNotBlank(billNoByObjId)) {
            //已生成单据编号，不继续生成新的单据编号
            return;
        }

//        if (bizObject == null) {
//            log.info("业务对象不存在");
//            return;
//        }
        //单据号
//        String sequenceNo = bizObject.getSequenceNo();
//        log.info("\n===============1-sequenceNo:{}", sequenceNo);

        String schemaCodeTableName = bizObjectFacade.getTableName(SchemaCode);
        //查询单据号changeRuleBySequenceNoExample02
        Calendar instance = Calendar.getInstance();
        Date nowTime = instance.getTime();
        String format = DateFormatUtils.format(nowTime, "yyyy-MM-dd");
        String startTimeString = new StringBuffer(format).append(" 00:00:00").toString();
        String endTimeString = new StringBuffer(format).append(" 23:59:59").toString();
        log.info("startTimeString：{}，endTimeString：{}", startTimeString, endTimeString);
        StringBuffer sqlCount = new StringBuffer("select billNo from ").append(schemaCodeTableName).append(" where sequenceStatus != 'DRAFT' and billNo is not null and billNo != '' and createdTime >= '")
                .append(startTimeString).append("' and createdTime <= '").append(endTimeString).append("' ORDER BY createdTime desc limit 1");
        Map<String, Object> djhCount = sqlService.getMap(sqlCount.toString());
        log.info("djhCount：{}", JSONObject.toJSONString(djhCount));
        String sequenceNo = "";
        String format2 = DateFormatUtils.format(nowTime, "yyyyMMdd");
        String billNoForLast2 = MapUtils.getString(djhCount, "billNo");
        if (djhCount == null || djhCount.size() == 0) {
            sequenceNo = new StringBuffer(format2).append("-").append(String.format("%03d", 1)).toString();
        } else {
            String substring = billNoForLast2.substring(billNoForLast2.length() - 3, billNoForLast2.length());
            int i = Integer.parseInt(substring) + 1;
            sequenceNo = new StringBuffer(format2).append("-").append(String.format("%03d", i)).toString();
        }


        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(SubSheet);
        //获取子表/主表对应字段
        String paramCode = (String) list.get(0).get(FormFieldValue);
        paramCode = StringUtils.isBlank(paramCode) ? (String) bizObject.get(FormFieldValue) : paramCode;


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String seqNo = simpleDateFormat.format(new Date());
        log.info("\n===============2-seqNo:{}", seqNo);
        if (StringUtils.isNoneBlank(sequenceNo)) {
            sequenceNo = seqNo + "-" + sequenceNo.substring(sequenceNo.length() - 3, sequenceNo.length());
            log.info("\n===============2-sequenceNo:{}", sequenceNo);
        }

        if (StringUtils.isBlank(FormFieldValue)) {
            sequenceNo = suffix + "-" + sequenceNo;
        } else {
            sequenceNo = suffix + "-" + paramCode + "-" + sequenceNo;
        }
        String billNo = sequenceNo;
        bizObject.put("billNo", billNo);
        //bizObject.put("name",bizObject.getCreater().getName()+"的 "+sequenceNo);
        bizObject.put("name", billNo);

        String workflowInstanceId = bizObject.getWorkflowInstanceId();
        log.info("----------------------------生成单据------------");
        scheduledExecutorService.schedule(() -> {
            if (StringUtils.isNotEmpty(workflowInstanceId)) {
                log.info("流程id存在:{}", workflowInstanceId);

                StringBuilder sql = new StringBuilder("update biz_workflow_instance set instanceName='")
                        .append(billNo).append("' where id='").append(workflowInstanceId).append("';");
                log.info("更新流程名称");
                sqlService.update(sql.toString());

                sql = new StringBuilder(" update biz_workitem set instanceName='").append(billNo).append("' where instanceId='")
                        .append(workflowInstanceId).append("';");
                log.info("更新待办流程名称");
                sqlService.update(sql.toString());

                log.info("更新已办流程名称");
                sql = new StringBuilder(" update biz_workitem_finished set instanceName='").append(billNo).append("' where instanceId='")
                        .append(workflowInstanceId).append("';");
            }

            getBizObjectFacade().saveBizObject("2c9280a26706a73a016706a93ccf002b", bizObject, Boolean.TRUE);
        }, 3, TimeUnit.SECONDS);


    }

    /**
     * 更改出表流程id生成规则 PUI-02.01-20190605-001
     * FormFieldValue 表单字段，SchemaCode 模型编码,suffix 后缀 如：PUI
     *
     * @param objId
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/changeRuleBySequenceNoExample02", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value = "更改表流程id生成规则", notes = "更改表流程id生成规则")
    public void changeRuleBySequenceNoExample02(String objId, String SchemaCode, String FormFieldValue, String SubSheet, String suffix, String InDate) {
        log.info("获取参数:objId={},SchemaCode={},FormFieldValue={},suffix={}", objId, SchemaCode, FormFieldValue, suffix);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(SchemaCode)) {
            log.info("参数不完整，直接结束");
            return;
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();

//        //因为节点是异步，单据号生成时好时不好怀疑代码进入，bizobject还没有生成，由于是节点简单处理直接sleep(并且不存在的id bizobject也不会为空）
//        for (int i = 0; i < 10 &&BooleanUtils.isNotTrue(bizObjectFacade.getBizObject(SchemaCode, objId).getLoadedFromDb()); i++) {
//            if(i==9){
//                log.info("业务对象不存在");
//                return ;
//            }
//            Thread.sleep(1000);
//        }
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(SchemaCode, objId);

        String billNoByObjId = bizObject.getString("billNo");
        if (StringUtils.isNotBlank(billNoByObjId)) {
            //已生成单据编号，不继续生成新的单据编号
            return;
        }

//        if (bizObject == null) {
//            log.info("业务对象不存在");
//            return;
//        }
        //单据号
//        String sequenceNo = bizObject.getSequenceNo();
//        log.info("\n===============1-sequenceNo:{}", sequenceNo);

        String schemaCodeTableName = bizObjectFacade.getTableName(SchemaCode);
        //查询单据号
        Calendar instance = Calendar.getInstance();
        Date nowTime = instance.getTime();
        String format = DateFormatUtils.format(nowTime, "yyyy-MM-dd");
        String startTimeString = new StringBuffer(format).append(" 00:00:00").toString();
        String endTimeString = new StringBuffer(format).append(" 23:59:59").toString();
        log.info("startTimeString：{}，endTimeString：{}", startTimeString, endTimeString);
        StringBuffer sqlCount = new StringBuffer("select billNo from ").append(schemaCodeTableName).append(" where sequenceStatus != 'DRAFT' and billNo is not null and billNo != '' and createdTime >= '")
                .append(startTimeString).append("' and createdTime <= '").append(endTimeString).append("' ORDER BY createdTime desc limit 1");
        Map<String, Object> djhCount = sqlService.getMap(sqlCount.toString());
        log.info("djhCount：{}", JSONObject.toJSONString(djhCount));
        String sequenceNo = "";
        String format2 = DateFormatUtils.format(nowTime, "yyyyMMdd");
        String billNoForLast2 = MapUtils.getString(djhCount, "billNo");
        if (djhCount == null || djhCount.size() == 0) {
            sequenceNo = new StringBuffer(format2).append("-").append(String.format("%03d", 1)).toString();
        } else {
            String substring = billNoForLast2.substring(billNoForLast2.length() - 3, billNoForLast2.length());
            int i = Integer.parseInt(substring) + 1;
            sequenceNo = new StringBuffer(format2).append("-").append(String.format("%03d", i)).toString();
        }


        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(SubSheet);
        //获取子表/主表对应字段
        String paramCode = (String) list.get(0).get(FormFieldValue);
        paramCode = StringUtils.isBlank(paramCode) ? (String) bizObject.get(FormFieldValue) : paramCode;

        Date IntoDate = (Date) list.get(0).get(InDate);
//        String IntoDateString = ObjectUtils.isEmpty(IntoDate) ? "" : "= '" + IntoDate.toString() + "'";

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String seqNo = simpleDateFormat.format(new Date());
        String IntoDateString = ObjectUtils.isEmpty(IntoDate) ? "" : simpleDateFormat.format(IntoDate);
        log.info("\n===============2-seqNo:{}", seqNo);
        if (StringUtils.isNoneBlank(sequenceNo)) {
            sequenceNo = seqNo + "-" + sequenceNo.substring(sequenceNo.length() - 3, sequenceNo.length());
            log.info("\n===============2-sequenceNo:{}", sequenceNo);
        }

        if (StringUtils.isBlank(FormFieldValue)) {
            sequenceNo = suffix + "-" + sequenceNo;
        } else {
            sequenceNo = suffix + "-" + paramCode + "-" + IntoDateString + sequenceNo.substring(sequenceNo.length() - 4, sequenceNo.length());
        }
        String billNo = sequenceNo;
        bizObject.put("billNo", billNo);
        //bizObject.put("name",bizObject.getCreater().getName()+"的 "+sequenceNo);
        bizObject.put("name", billNo);

        String workflowInstanceId = bizObject.getWorkflowInstanceId();

        scheduledExecutorService.schedule(() -> {
            if (StringUtils.isNotEmpty(workflowInstanceId)) {
                log.info("流程id存在:{}", workflowInstanceId);

                StringBuilder sql = new StringBuilder("update biz_workflow_instance set instanceName='")
                        .append(billNo).append("' where id='").append(workflowInstanceId).append("';");
                log.info("更新流程名称");
                sqlService.update(sql.toString());

                sql = new StringBuilder(" update biz_workitem set instanceName='").append(billNo).append("' where instanceId='")
                        .append(workflowInstanceId).append("';");
                log.info("更新待办流程名称");
                sqlService.update(sql.toString());

                log.info("更新已办流程名称");
                sql = new StringBuilder(" update biz_workitem_finished set instanceName='").append(billNo).append("' where instanceId='")
                        .append(workflowInstanceId).append("';");
            }

            getBizObjectFacade().saveBizObject("2c9280a26706a73a016706a93ccf002b", bizObject, Boolean.TRUE);
        }, 3, TimeUnit.SECONDS);


    }

    /**
     * 根据规则生成事项编码：ER+公司代码+发生日期+序号
     *
     * @param id
     * @param schemaCode
     * @param childTableSchemaCode
     * @param formFieldValue
     * @param itemCodeField
     * @return
     */
    @GetMapping(value = "/generateItemCode1")
    @ApiOperation(value = "根据规则生成事项编码")
    @SuppressWarnings("unchecked")
    public ResponseResult<Void> generateItemCode1(String id, String schemaCode, String childTableSchemaCode, String formFieldValue, String itemCodeField) {
        log.info("方法generateItemCode请求参数，id：{}，schemaCode：{}，childTableSchemaCode：{}，formFieldValue：{}，itemCodeField：{}", id, schemaCode, childTableSchemaCode, formFieldValue, itemCodeField);
        // 获取业务数据
        BizObjectCreatedModel bizObject = this.getBizObjectFacade().getBizObject(schemaCode, id);
        log.info("业务模型数据:{}", JSON.toJSONString(bizObject));
        if (bizObject == null || MapUtil.isEmpty(bizObject.getData())) {
            throw new PortalException(ErrCode.BIZ_OBJECT_NOT_EXIST);
        }
        Lock lock = this.redisson.getLock("cloudpivot:itemCode" + schemaCode);
        boolean locked = false;
        try {
            locked = lock.tryLock(10L, TimeUnit.SECONDS);
            if (!locked) {
                throw new PortalException(ErrCode.SYS_BUSINESS_DOING_ERROR.getErrCode(), "当前模型正在生成事项编码，不能重复执行");
            }
            List<Map<String, Object>> childList = (List<Map<String, Object>>) bizObject.get(childTableSchemaCode);
            // 获取公司代码
            String companyCode = MapUtil.getStr(childList.get(0), formFieldValue, "");

            // 根据获取日期查询数据库，获取序号最大值
            BizObjectQueryModel bizObjectQueryModel = new BizObjectQueryModel();
            bizObjectQueryModel.setSchemaCode(schemaCode);
            bizObjectQueryModel.setQueryCode(schemaCode);
            bizObjectQueryModel.setPageable(new PageableImpl(0, Integer.MAX_VALUE));
            List<FilterExpression> filterExpressionList = Lists.newArrayList();
            Date date = new Date();
            filterExpressionList.add(Q.it(DefaultPropertyType.CREATED_TIME.getCode(), FilterExpression.Op.Gte, DateUtil.format(date, DatePattern.NORM_DATE_PATTERN).concat(" 00:00:00")));
            filterExpressionList.add(Q.it(DefaultPropertyType.CREATED_TIME.getCode(), FilterExpression.Op.Lt, DateUtil.format(date, DatePattern.NORM_DATE_PATTERN).concat(" 23:59:59")));
            filterExpressionList.add(Q.it(itemCodeField, FilterExpression.Op.NotEq, null));
            bizObjectQueryModel.setFilterExpr(Q.and(filterExpressionList));
            bizObjectQueryModel.setOrderType(1);
            bizObjectQueryModel.setOrderByFields(Collections.singletonList(itemCodeField));
            Page<BizObjectModel> bizObjectModelPage = this.getBizObjectFacade().queryBizObjects(bizObjectQueryModel);
            List<? extends BizObjectModel> content = bizObjectModelPage.getContent();
            log.info("查询结果bizObjectModelPage：{}", JSONObject.toJSONString(bizObjectModelPage));
            String itemCode = "";
            if (bizObjectModelPage.getTotal() == 0) {
                log.info("今天未生成数据，从001开始");
                // 说明今天未生成数据，从001开始
                itemCode = "ER".concat("-").concat(companyCode).concat("-").concat(DateUtil.format(date, DatePattern.PURE_DATE_PATTERN)).concat("-").concat("001");
            } else {
                // 获取当前最大事项编号
                BizObjectModel bizObjectModel = bizObjectModelPage.getContent().get(0);
                log.info("bizObjectModel:{}", JSONObject.toJSONString(bizObjectModel));
                log.info("itemCodeField:{}", itemCodeField);
                log.info("bizObjectModelPage.getContent().get(0).get(itemCodeField)结果:{}", bizObjectModelPage.getContent().get(0).get(itemCodeField));
                String currentItemCode = String.valueOf(bizObjectModelPage.getContent().get(0).get(itemCodeField));
                log.info("currentItemCode:{}", currentItemCode);
                if (StringUtils.isBlank(currentItemCode)) {
                    // 说明之前的表单未生成数据，从001开始
                    log.info("之前的表单未生成数据，从001开始:{}", currentItemCode);
                    itemCode = "ER".concat("-").concat(companyCode).concat("-").concat(DateUtil.format(date, DatePattern.PURE_DATE_PATTERN)).concat("-").concat("001");
                } else {
                    int number = Integer.parseInt(currentItemCode.substring(currentItemCode.length() - 3));
                    if (number == 999) {
                        log.info("number1:{}", number);
                        // 最大为999
                        itemCode = "ER".concat("-").concat(companyCode).concat("-").concat(DateUtil.format(date, DatePattern.PURE_DATE_PATTERN)).concat("-").concat("999");
                        log.info("itemCode1:{}", itemCode);
                    } else {
                        ++number;
                        log.info("number2:{}", number);
                        itemCode = "ER".concat("-").concat(companyCode).concat("-").concat(DateUtil.format(date, DatePattern.PURE_DATE_PATTERN)).concat("-").concat(String.format("%03d", number));
                        log.info("itemCode2:{}", itemCode);
                    }
                }
            }
            // 修改事项编码
            bizObject.put(itemCodeField, itemCode);
            log.info("最后修改前：{}", itemCode);
            this.getBizObjectFacade().saveBizObject("2c9280a26706a73a016706a93ccf002b", bizObject, Boolean.TRUE);
        } catch (Exception e) {
            log.error("生成事项编码出错，错误信息：{}", e.getMessage());
            throw new PortalException(ErrCode.UNKNOW_ERROR.getErrCode(), "服务异常！");
        } finally {
            if (locked) {
                lock.unlock();
            }
        }
        return this.getOkResponseResult("生成事项编码成功");
    }


    /**
     * 根据规则生成事项编码：ER+公司代码+发生日期+序号
     * ER（先固定ER，后面优化，从主表中取）
     * companyNumber  子表公司代码的数据项编码，公司代码从子表取
     * Date  子表发生日期的数据项编码，发生日期从子表取
     * 序号
     * <p>
     * 生成的事项编码赋值到子表中，所以序号也从子表取
     * numberFlag  子表中的序号标识
     *
     * @param id                   表单id
     * @param schemaCode           模型编码
     * @param childTableSchemaCode 子表编码
     * @param formFieldValue       子表
     * @param itemCodeField        子表赋值-传入问题项代码的数据项编码
     * @return
     */
    @GetMapping(value = "/generateItemCode2")
    @ApiOperation(value = "根据规则生成事项编码")
    @SuppressWarnings("unchecked")
    public ResponseResult<Void> generateItemCode2(String id, String schemaCode, String childTableSchemaCode, String formFieldValue, String itemCodeField) {
        log.info("方法generateItemCode请求参数，id：{}，schemaCode：{}，childTableSchemaCode：{}，formFieldValue：{}，itemCodeField：{}", id, schemaCode, childTableSchemaCode, formFieldValue, itemCodeField);
        // 获取业务数据
        BizObjectCreatedModel bizObject = this.getBizObjectFacade().getBizObject(schemaCode, id);
        log.info("业务模型数据:{}", JSON.toJSONString(bizObject));
        if (bizObject == null || MapUtil.isEmpty(bizObject.getData())) {
            throw new PortalException(ErrCode.BIZ_OBJECT_NOT_EXIST);
        }


        String sql = "select numberFlag from i28by_SheetRpRecord ORDER BY numberFlag desc";
        List<Map<String, Object>> list = sqlService.getList(sql);
        Integer numberFlag = 0;
        if (list != null && list.size() > 0) {
            //说明子表中已经存在数据，需要判断序号
            Map<String, Object> stringObjectMap = list.get(0);
            numberFlag = StringUtils.isBlank((String) stringObjectMap.get("numberFlag")) ? 1 : Integer.valueOf((String) stringObjectMap.get("numberFlag"));
        } else {
            //说明子表中不存在数据，需要判断序号
        }


        try {
            List<Map<String, Object>> childList = (List<Map<String, Object>>) bizObject.get(childTableSchemaCode);
            for (Map<String, Object> stringObjectMap : childList) {

            }


            // 获取公司代码
            String companyCode = MapUtil.getStr(childList.get(0), formFieldValue, "");

            // 根据获取日期查询数据库，获取序号最大值
            BizObjectQueryModel bizObjectQueryModel = new BizObjectQueryModel();
            bizObjectQueryModel.setSchemaCode(schemaCode);
            bizObjectQueryModel.setQueryCode(schemaCode);
            bizObjectQueryModel.setPageable(new PageableImpl(0, Integer.MAX_VALUE));
            List<FilterExpression> filterExpressionList = Lists.newArrayList();
            Date date = new Date();
            filterExpressionList.add(Q.it(DefaultPropertyType.CREATED_TIME.getCode(), FilterExpression.Op.Gte, DateUtil.format(date, DatePattern.NORM_DATE_PATTERN).concat(" 00:00:00")));
            filterExpressionList.add(Q.it(DefaultPropertyType.CREATED_TIME.getCode(), FilterExpression.Op.Lt, DateUtil.format(date, DatePattern.NORM_DATE_PATTERN).concat(" 23:59:59")));
            filterExpressionList.add(Q.it(itemCodeField, FilterExpression.Op.NotEq, null));
            bizObjectQueryModel.setFilterExpr(Q.and(filterExpressionList));
            bizObjectQueryModel.setOrderType(1);
            bizObjectQueryModel.setOrderByFields(Collections.singletonList(itemCodeField));
            Page<BizObjectModel> bizObjectModelPage = this.getBizObjectFacade().queryBizObjects(bizObjectQueryModel);
            List<? extends BizObjectModel> content = bizObjectModelPage.getContent();
            log.info("查询结果bizObjectModelPage：{}", JSONObject.toJSONString(bizObjectModelPage));
            String itemCode = "";
            if (bizObjectModelPage.getTotal() == 0) {
                log.info("今天未生成数据，从001开始");
                // 说明今天未生成数据，从001开始
                itemCode = "ER".concat("-").concat(companyCode).concat("-").concat(DateUtil.format(date, DatePattern.PURE_DATE_PATTERN)).concat("-").concat("001");
            } else {
                // 获取当前最大事项编号
                BizObjectModel bizObjectModel = bizObjectModelPage.getContent().get(0);
                log.info("bizObjectModel:{}", JSONObject.toJSONString(bizObjectModel));
                log.info("itemCodeField:{}", itemCodeField);
                log.info("bizObjectModelPage.getContent().get(0).get(itemCodeField)结果:{}", bizObjectModelPage.getContent().get(0).get(itemCodeField));
                String currentItemCode = String.valueOf(bizObjectModelPage.getContent().get(0).get(itemCodeField));
                log.info("currentItemCode:{}", currentItemCode);
                if (StringUtils.isBlank(currentItemCode)) {
                    // 说明之前的表单未生成数据，从001开始
                    log.info("之前的表单未生成数据，从001开始:{}", currentItemCode);
                    itemCode = "ER".concat("-").concat(companyCode).concat("-").concat(DateUtil.format(date, DatePattern.PURE_DATE_PATTERN)).concat("-").concat("001");
                } else {
                    int number = Integer.parseInt(currentItemCode.substring(currentItemCode.length() - 3));
                    if (number == 999) {
                        log.info("number1:{}", number);
                        // 最大为999
                        itemCode = "ER".concat("-").concat(companyCode).concat("-").concat(DateUtil.format(date, DatePattern.PURE_DATE_PATTERN)).concat("-").concat("999");
                        log.info("itemCode1:{}", itemCode);
                    } else {
                        ++number;
                        log.info("number2:{}", number);
                        itemCode = "ER".concat("-").concat(companyCode).concat("-").concat(DateUtil.format(date, DatePattern.PURE_DATE_PATTERN)).concat("-").concat(String.format("%03d", number));
                        log.info("itemCode2:{}", itemCode);
                    }
                }
            }
            // 修改事项编码
            bizObject.put(itemCodeField, itemCode);
            log.info("最后修改前：{}", itemCode);
            this.getBizObjectFacade().saveBizObject("2c9280a26706a73a016706a93ccf002b", bizObject, Boolean.TRUE);
        } catch (Exception e) {
            log.error("生成事项编码出错，错误信息：{}", e.getMessage());
            throw new PortalException(ErrCode.UNKNOW_ERROR.getErrCode(), "服务异常！");
        } finally {
        }
        return this.getOkResponseResult("生成事项编码成功");
    }

    /**
     * 根据规则生成事项编码：ER+公司代码+发生日期+序号
     * ER（先固定ER，后面优化，从主表中取）
     * companyNumber  子表公司代码的数据项编码，公司代码从子表取
     * Date  子表发生日期的数据项编码，发生日期从子表取
     * 序号
     * <p>
     * 生成的事项编码赋值到子表中，所以序号也从子表取
     * numberFlag  子表中的序号标识
     *
     * @param schemaCode     主表编码
     * @param childTableCode 子表表单编码
     * @param timeString     时间  2023-01-18  需要转换为20230118
     * @return
     */
    @GetMapping(value = "/generateItemCode3")
    @ApiOperation(value = "根据规则生成事项编码")
    @SuppressWarnings("unchecked")
    public String generateItemCode3(@RequestParam String schemaCode, String childTableCode, @RequestParam String timeString) {
        //timeString  2023-01-18转换为20230118
//        String replace = timeString.replace("-", "");
        BizObjectFacade bizObjectFacade = getBizObjectFacade();
        String itemNumberCounter = bizObjectFacade.getTableName("ItemNumberCounter");
        StringBuffer selectSql = new StringBuffer("select * from ").append(itemNumberCounter).append(" where timeString = '")
                .append(timeString).append("' and schemaCodeForCount = '").append(schemaCode).append("' order by count desc limit 1");
        Map<String, Object> map = sqlService.getMap(selectSql.toString());
        Integer count = MapUtils.getInteger(map, "count", 0);
        if (count == 0) {
            count += 1;
            Map<String, Object> data = new HashMap<>();
            data.put("timeString", timeString);
            data.put("count", count);
            data.put("schemaCodeForCount", schemaCode);
            BizObjectCreatedModel model = new BizObjectCreatedModel("ItemNumberCounter", data, false);
            model.setSequenceStatus(SequenceStatus.COMPLETED.name());
            getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
        } else {
            count += 1;
            Map<String, Object> data = new HashMap<>();
            data.put("id", MapUtils.getString(map, "id"));
            data.put("count", count);
            BizObjectCreatedModel model = new BizObjectCreatedModel("ItemNumberCounter", data, false);
            model.setSequenceStatus(SequenceStatus.COMPLETED.name());
            getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
        }
        String format = String.format("%03d", count);
        return format;
    }

    @PostMapping(value = "/generateItemCode3CheckExistence")
    @ApiOperation(value = "校验事项编码是否存在")
    public ResponseResult<List<Map<String, Object>>> generateItemCode3CheckExistence(@RequestBody Map<String, Object> parma) {

//        String schemaCode = MapUtils.getString(parma, "schemaCode");
        String childTableCode = MapUtils.getString(parma, "childTableCode");
        String childTableName = getBizObjectFacade().getTableName(childTableCode);
        List<Map<String, Object>> itemNumberAndPersonNumberList = (List<Map<String, Object>>) parma.get("itemNumberAndPersonNumberList");

        //暂时不对传入的集合做去重处理
//        List<Map<String, Object>> itemNumberAndPersonNumberQueryList = new ArrayList<>();
//        for (Map<String, Object> map : itemNumberAndPersonNumberList) {
//            if (!itemNumberAndPersonNumberQueryList.contains(map)) {
//                itemNumberAndPersonNumberQueryList.add(map);
//            }
//        }

        List<Map<String, Object>> returnList = new ArrayList<>();
        for (Map<String, Object> map : itemNumberAndPersonNumberList) {
            //每行数据进行校验
            String itemNumber = MapUtils.getString(map, "itemNumber");
            String personNumber = MapUtils.getString(map, "personNumber");
            String numberOfRows = MapUtils.getString(map, "numberOfRows");
            //做校验的时候
            StringBuffer sql = new StringBuffer("select id  from ").append(childTableName)
                    .append(" where personNumber='").append(personNumber)
                    .append("' and itemNumber='").append(itemNumber)
                    .append("';");
            Map<String, Object> data = sqlService.getMap(sql.toString());

            String id = MapUtils.getString(data, "id", "");
            if (StringUtils.isNotBlank(id)) {
                //不为空说明此人员代码和事项代码的组合已经在数据库存在
                HashMap<String, Object> returnMap = new HashMap<>();
                returnMap.put("itemNumber", itemNumber);
                returnMap.put("personNumber", personNumber);
                returnMap.put("numberOfRows", numberOfRows);
                returnList.add(returnMap);
            }
        }

        return this.getOkResponseResult(returnList, "校验完成");
    }


    /**
     * 根据规则生成事项编码：ER+公司代码+发生日期+序号
     * ER（先固定ER，后面优化，从主表中取）
     * companyNumber  子表公司代码的数据项编码，公司代码从子表取
     * Date  子表发生日期的数据项编码，发生日期从子表取
     * 序号
     * <p>
     * 生成的事项编码赋值到子表中，所以序号也从子表取
     * numberFlag  子表中的序号标识
     *
     * @param schemaCode     主表编码
     * @param childTableCode 子表表单编码
     * @param timeString     时间  2023-01-18  需要转换为20230118
     * @return
     */
    @GetMapping(value = "/generateItemCode4")
    @ApiOperation(value = "根据规则生成事项编码")
    @SuppressWarnings("unchecked")
    public String generateItemCode4(@RequestParam String schemaCode, String childTableCode, @RequestParam String timeString) {
        //timeString  2023-01-18转换为20230118
//        String replace = timeString.replace("-", "");
        BizObjectFacade bizObjectFacade = getBizObjectFacade();
        String itemNumberCounter = bizObjectFacade.getTableName("ItemNumberCounter");
        StringBuffer selectSql = new StringBuffer("select * from ").append(itemNumberCounter).append(" where timeString = '")
                .append(timeString).append("' and schemaCodeForCount = '").append(schemaCode).append("' order by count desc limit 1");
        Map<String, Object> map = sqlService.getMap(selectSql.toString());
        Integer count = MapUtils.getInteger(map, "count", 0);
        if (count == 0) {
            count += 1;
            Map<String, Object> data = new HashMap<>();
            data.put("timeString", timeString);
            data.put("count", count);
            data.put("schemaCodeForCount", schemaCode);
            BizObjectCreatedModel model = new BizObjectCreatedModel("ItemNumberCounter", data, false);
            model.setSequenceStatus(SequenceStatus.COMPLETED.name());
            getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
        } else {
            count += 1;
            Map<String, Object> data = new HashMap<>();
            data.put("id", MapUtils.getString(map, "id"));
            data.put("count", count);
            BizObjectCreatedModel model = new BizObjectCreatedModel("ItemNumberCounter", data, false);
            model.setSequenceStatus(SequenceStatus.COMPLETED.name());
            getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
        }
        String format = String.format("%03d", count);
        return format;
    }


}
